#include "ServerNetwork.h"

using namespace std;
ServerNetwork::ServerNetwork(void)
{
	mSocket = new CPassiveSocket(CSimpleSocket::SocketTypeTcp);

	cout << "Socket Error:" << mSocket->GetSocketError() << endl;

	mSocket->Initialize();
	
	cout << "Socket Error:" << mSocket->GetSocketError() << endl;

	mSocket->Listen((const unsigned char *)"127.0.0.1", 8090);

	cout << "Socket Error:" << mSocket->GetSocketError() << endl;

	mSocket->SetBlocking();

	// If set to blocking, re-enable threading in RequestDispatcher
}


ServerNetwork::~ServerNetwork(void)
{
	mSocket->Close();
	delete mSocket;
}

Client *ServerNetwork::GetClient()
{
	// Accept, blocking
	Client *cSocket = nullptr;

	CActiveSocket *socket = nullptr;

	socket = mSocket->Accept();
	//cout << "Failed error: " << mSocket->GetSocketError() << "   " << rand() << endl;
	if(socket != nullptr)
	{
		cSocket = new Client(socket);
		
		//cout << "Got Client: " << socket->GetClientAddr() << endl;

		socket->SetBlocking();
		socket->SetReceiveTimeout(2);
	}

	return cSocket;
}
